<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\lib\baidu\Api as baiduApi;

class AiCreateProblem extends Command
{
    protected function configure() {
        $this->setName('AiCreateProblem')->setDescription("生成题库");
    }

    protected function execute(Input $input, Output $output) {
        ini_set('max_execution_time', 0);
        set_time_limit(0);

        while(true){
            $starttime = time();
            try{
                $rules = Db::name('problem_create')->where('status','in',[0,1])->select();
                if (empty($rules)) {
                    exit('empty rule');
                }

                $api = new baiduApi();
                $api_param = json_decode('{"client_id":"2UdtilsxkinLDnwwvQUj1Dif","client_secret":"sU8i7ce6KBVBKFdjpBEveUFfcTNoHKcG"}',true);
                $token = $api->token($api_param);
                if (empty($token['access_token'])) {
                    return json(['code'=>5000,'msg'=>'token获取失败']);
                }

                foreach ($rules as $rule) {
                    $max_num = $rule['type'] == 1 ? 30 : 80;
                    if ($rule['num'] >= $max_num) {
                        Db::name('problem_create')->where('id',$rule['id'])->update(['status'=>2]);
                        continue;
                    }
                    $knowledge = $rule['knowledge'];
                    $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/'.$knowledge.'/?access_token='.$token['access_token'];

                    $history = [];
                    $list = Db::name('problem_tmp')->where('create_id',$rule['id'])->select();
                    foreach ($list as $k => $vo) {
                        $content = $vo['content'];
                        if ($rule['mode'] > 0) {
                            $content = str_replace(['```json','json```','```'], '', $vo['content']);
                            $content = str_replace("\n", "", $content); // 换行导致json无法解析
                            $content = json_decode($content,true);
                            if ($rule['mode'] >= 1) {
                                unset($content['analysis']);
                            }
                            if ($rule['mode'] >= 2) {
                                unset($content['answer']);
                            }
                            if ($rule['mode'] >= 3) {
                                unset($content['options']);
                            }
                            $content = '```json
        '.json_encode($content,JSON_UNESCAPED_UNICODE).'
        ```';
                        }
           
                        $history[] = [
                            'role'=>'user',
                            'content'=>'1'
                        ];
                        $history[] = [
                            'role'=>'assistant',
                            'content'=>$content
                        ];
                    }
                    while ($rule['num'] < $max_num) {
                        $params = [
                            'query'=>'1',
                            'llm'=>[
                                'temperature'=>1,
                                'top_p'=>1,
                                'penalty_score'=>1
                            ],
                            'verbose'=>false,
                        ];
                        if (!empty($history)) {
                            $params['history'] = $history;
                        }
                        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',['Content-Type: application/json']);
                        $result = json_decode($result,true);
                        if (!empty($result['error_code'])) {
                            if (strpos($result['error_msg'], '336103') !== false) {
                                Db::name('problem_create')->where('id',$rule['id'])->update(['mode'=>$rule['mode']+1]);
                                throw new \Exception("next"); 
                            }
                            return json(['code'=>5000,'msg'=>$result['error_msg']]);
                        }

                        $content = $history[count($history)-1]['content'];
                        if ($rule['mode'] > 0) {
                            $content = str_replace(['```json','json```','```'], '', $vo['content']);
                            $content = str_replace("\n", "", $content); // 换行导致json无法解析
                            $content = json_decode($content,true);
                            if ($rule['mode'] >= 1) {
                                unset($content['analysis']);
                            }
                            if ($rule['mode'] >= 2) {
                                unset($content['answer']);
                            }
                            if ($rule['mode'] >= 3) {
                                unset($content['options']);
                            }
                            $content = '```json
        '.json_encode($content,JSON_UNESCAPED_UNICODE).'
        ```';
                            $history[count($history)-1]['content'] = $content;
                        }

                        $history[] = [
                            'role'=>'user',
                            'content'=>'1'
                        ];
                        $history[] = [
                            'role'=>'assistant',
                            'content'=>$result['result']
                        ];

                        Db::name('problem_tmp')->insert(['content'=>$result['result'],'create_id'=>$rule['id'],'mode'=>$rule['mode']]);
                        Db::name('problem_create')->where('id',$rule['id'])->inc('num')->update();
                        $rule['num']++;
                    }
                }
            } catch (\Exception $e) {
                sleep(5);
                continue;
            }
            sleep(5);
        }
    }
}